package notify

import (
	"APT/internal/consts"
	"APT/internal/dao"
	"APT/internal/library/MobilePush"
	"APT/internal/model/entity"
	"APT/internal/model/input/input_basics"
	"APT/internal/websocket"
	"APT/utility/simple"
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"strings"

	"github.com/gogf/gf/v2/errors/gerror"

	"APT/api/notify/hook"
)

func (c *ControllerHook) VisitorMessageCallUrl(ctx context.Context, req *hook.VisitorMessageCallUrlReq) (res *hook.VisitorMessageCallUrlRes, err error) {
	var (
		in            *input_basics.NoticeEditInp
		MemberInfo    *entity.AdminMember
		PmsMemberInfo *entity.PmsMember
	)
	g.Log().Path("logs/HOOK/KEFU_HOOK").Debugf(ctx, "req: %#v", req)
	res = new(hook.VisitorMessageCallUrlRes)
	if req.Type == "in" {
		if err = dao.AdminMember.Ctx(ctx).Where(g.MapStrAny{
			dao.AdminMember.Columns().KefuAccount: req.To,
		}).Scan(&MemberInfo); err != nil {
			g.Log().Path("logs/HOOK/KEFU_HOOK").Error(ctx, err)
			err = gerror.New("用户信息异常")
			return
		}
		if g.IsEmpty(MemberInfo) {
			err = gerror.New("用户信息异常")
			return
		}
		in = new(input_basics.NoticeEditInp)
		if req.From == "order" {
			in.Title = "订单新消息通知"
			in.Type = consts.NoticeTypeOrderHandle
		} else {
			in.Title = "客服新消息通知"
			in.Type = consts.NoticeTypeLetter
		}
		in.Content = req.Content
		in.Receiver = []int64{MemberInfo.Id}
		// 新增
		in.CreatedBy = MemberInfo.Id
		in.CreatedAt = gtime.Now()
		// 推送通知
		response := &websocket.WResponse{
			Event: "notice",
			Data:  in,
		}
		simple.SafeGo(ctx, func(ctx context.Context) {
			if in.Type == consts.NoticeTypeLetter {
				for _, receiverId := range in.Receiver {
					websocket.SendToUser(receiverId, response)
				}
			} else {
				websocket.SendToAll(response)
			}
		})
	} else if req.Type == "out" {
		// 向客户推送通知
		memberIds := strings.Split(req.To, "|")
		if len(memberIds) > 1 && !g.IsEmpty(memberIds[1]) {
			memberId := memberIds[1]
			// 查询用户信息
			if err = dao.PmsMember.Ctx(ctx).Where(g.MapStrAny{
				dao.PmsMember.Columns().Id: memberId,
			}).Scan(&PmsMemberInfo); err != nil {
				g.Log().Path("logs/HOOK/KEFU_HOOK").Error(ctx, err)
				return
			}
			if !g.IsEmpty(PmsMemberInfo) {
				if err = MobilePush.SendPush(ctx, "customer service message", "You have a customer service message", g.SliceStr{PmsMemberInfo.MemberNo}); err != nil {
					g.Log().Path("logs/HOOK/KEFU_HOOK").Error(ctx, err)
					return
				}
			}
		}
	}
	g.Log().Path("logs/HOOK/KEFU_HOOK").Info(ctx, "——————————————————————————————————————————————————————————————————————————————————————————")
	g.Log().Path("logs/HOOK/KEFU_HOOK").Info(ctx, req)
	return
}
